package com.mall.shopping.services;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.shopping.IProductService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.ContentConverter;
import com.mall.shopping.converter.ProductConverter;
import com.mall.shopping.converter.ProductDetailedConverter;
import com.mall.shopping.converter.TestProductDetailConverter;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.entitys.ItemDesc;
import com.mall.shopping.dal.entitys.Panel;
import com.mall.shopping.dal.entitys.PanelContentItem;
import com.mall.shopping.dal.persistence.ItemDescMapper;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dal.persistence.PanelContentMapper;
import com.mall.shopping.dal.persistence.PanelMapper;
import com.mall.shopping.dto.*;
import com.mall.shopping.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Walkden Piao
 * @version 1.0
 */
@Service
@Slf4j
public class IProductServiceImpl implements IProductService {
    @Autowired
    ItemMapper itemMapper;
    @Autowired
    ItemDescMapper itemDescMapper;
    @Autowired
    PanelMapper panelMapper;
    @Autowired
    PanelContentMapper panelContentMapper;
    @Autowired
    ProductDetailedConverter productDetailedConverter;
    @Autowired
    ProductConverter productConverter;
    @Autowired
    ContentConverter contentConverter;

    @Override
    public ProductDetailResponse getProductDetail(ProductDetailRequest request) {
        ProductDetailResponse productDetailResponse = new ProductDetailResponse();
        try {
            //检查参数
            request.requestCheck();
            Item item = itemMapper.selectByPrimaryKey(request.getId());
            ProductDetailDto productDetailDto1 = productDetailedConverter.item2Dto(item);


            ItemDesc itemDesc = itemDescMapper.selectByPrimaryKey(request.getId());
            String itemDesc1 = itemDesc.getItemDesc();
            productDetailDto1.setDetail(itemDesc1);

            //string数组转list
            String[] images = item.getImages();
            List<String> strings = Arrays.asList(images);
            productDetailDto1.setProductImageSmall(strings);
            System.out.println(productDetailDto1);
            productDetailResponse.setProductDetailDto(productDetailDto1);
            productDetailResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            productDetailResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            //响应失败
            log.info("IProductServiceImpl#getProductDetail " + e);
            productDetailResponse.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
            productDetailResponse.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
        }

        return productDetailResponse;

    }

    /**
     * 查询所有商品（分页）
     * @param request 请求参数
     * @return AllProductResponse
     */
    @Override
    public AllProductResponse getAllProduct(AllProductRequest request) {
        // 响应封装类
        AllProductResponse response = new AllProductResponse();

        try {
            request.requestCheck();
        } catch (RuntimeException e) {
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
            return response;
        }

        try {
            //分页
            PageHelper.startPage(request.getPage(), request.getSize());
            // 0不排序 1从低到高排序 -1从高到低
            String sort = request.getSort();
            BigDecimal priceMin = request.getPriceGt();
            BigDecimal priceMax = request.getPriceLte();
            //查询
            Example itemExample = new Example(Item.class);
            if (sort.equals("1")) { // 价格从低到高
                itemExample.setOrderByClause("price ASC");
            } else if (sort.equals("-1")) {
                itemExample.setOrderByClause("price DESC");
            }

            Example.Criteria criteria = itemExample.createCriteria();
            if (priceMin != null)
                criteria.andGreaterThanOrEqualTo("price", priceMin);
            if (priceMax != null)
                criteria.andLessThanOrEqualTo("price", priceMax);

            List<Item> items = itemMapper.selectByExample(itemExample);
            // 查询结果放进来
            PageInfo<Item> itemCatPageInfo = new PageInfo<>(items);
            // 总的数据量
            long total = itemCatPageInfo.getTotal();
            // 转换对象
            List<ProductDto> productDtos = productConverter.items2Dto(items);

            // 封装
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            response.setTotal(total);
            response.setProductDtoList(productDtos);
        } catch (Exception e) {
            log.error("ProductServiceImpl.getAllProduct occur error :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public RecommendResponse getRecommendGoods() {
        Integer id = 6;
        RecommendResponse recommendResponse = new RecommendResponse();
        Panel panel = panelMapper.selectByPrimaryKey(id);
        PanelDto panelDto = contentConverter.panen2Dto(panel);
        List<PanelContentItem> panelContentItems = panelContentMapper.selectPanelContentAndProductWithPanelId(id);
        System.out.println(panelContentItems);
        List<PanelContentItemDto> panelContentItemDtos = contentConverter.panelContentItem2Dto(panelContentItems);
        System.out.println(panelContentItemDtos);
        panelDto.setPanelContentItems(panelContentItemDtos);
        Set<PanelDto> panelDtos = new HashSet<>();
        panelDtos.add(panelDto);
        recommendResponse.setPanelContentItemDtos(panelDtos);
        recommendResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
        recommendResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        return recommendResponse;
    }

}
